//
//  XOClubCommentViewController.m
//  didigo
//
//  Created by JS_Coder on 2019/3/2.
//  Copyright © 2019 lifayu. All rights reserved.
//

#import "XOClubCommentViewController.h"
#import "XOClubViewModel.h"
#import "XOClubMessageCell.h"
#import "XOClubDetailCommentCell.h"
#import <IQKeyboardManager.h>
#import "EJSClubCommentRequest.h"
#import <SVProgressHUD.h>
#define SubmitButtonWitdh 44
#define BaseViewHeight 64
@interface XOClubCommentViewController () <UITableViewDelegate, UITableViewDataSource,UITextViewDelegate>
StrongProperty UITableView * tableView;
StrongProperty UIView * inputBaseView;
StrongProperty UITextView * textView;
StrongProperty UIButton *submitButton;
@end

@implementation XOClubCommentViewController
    //MARK: - Vars.
- (UIView *)inputBaseView {
    if (_inputBaseView != NULL) {
        return _inputBaseView;
    }
    _inputBaseView = [[UIView alloc]initWithFrame:CGRectMake(0, self.view.bounds.size.height - BaseViewHeight - NavigationBarHeight - StatusBarHeight - BottomIdicatorHeight, ScreenWidth, BaseViewHeight)];
    _inputBaseView.backgroundColor = UIColor.whiteColor;
    return _inputBaseView;
}

- (UITextView *)textView {
    if (_textView != NULL) {
        return _textView;
    }
    _textView = [[UITextView alloc]initWithFrame:CGRectMake(10, 10, ScreenWidth - SubmitButtonWitdh - 20, BaseViewHeight - 20)];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    _textView.backgroundColor = UIColorFromRGB(0xF5F5F5);
    _textView.textColor = UIColor.darkGrayColor;
    _textView.text = @"请输入评论";
    _textView.delegate = self;
    return _textView;
}

- (UIButton *)submitButton {
    if (_submitButton != NULL) {
        return _submitButton;
    }
    _submitButton = [[UIButton alloc]initWithFrame:CGRectMake(ScreenWidth - SubmitButtonWitdh - 5, 0 , SubmitButtonWitdh, BaseViewHeight)];

    [_submitButton setImage:[UIImage imageNamed:@"submit_normal"] forState:UIControlStateNormal];
    [_submitButton setImage:[UIImage imageNamed:@"submit_select"] forState:UIControlStateHighlighted];
    [_submitButton addTarget:self action:@selector(submitButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return _submitButton;
}

- (UITableView *)tableView {
    if (_tableView != NULL) {
        return _tableView;
    }
    CGRect frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight - NavigationBarHeight - BaseViewHeight);
    _tableView = [[UITableView alloc]initWithFrame:frame style:UITableViewStylePlain];
    [_tableView registerNib:[UINib nibWithNibName:@"XOClubMessageCell" bundle:nil] forCellReuseIdentifier:@"CommentXOClubMessageCell"];
    [_tableView registerNib:[UINib nibWithNibName:@"XOClubDetailCommentCell" bundle:nil] forCellReuseIdentifier:@"XOClubDetailCommentCell"];
    _tableView.estimatedRowHeight = 300;
    _tableView.backgroundColor = UIColor.clearColor;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    return _tableView;
}

    //MARK: - Life
- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[IQKeyboardManager sharedManager] setEnable:NO];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:NO];
    [[IQKeyboardManager sharedManager] setLayoutIfNeededOnUpdate:NO];

}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [XOClubViewModel shared].isComment = NO;
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [[IQKeyboardManager sharedManager] setEnableAutoToolbar:YES];
    [[IQKeyboardManager sharedManager] setLayoutIfNeededOnUpdate:YES];
}

- (void)configOwnViews {
    self.view.backgroundColor = UIColorFromRGB(0xF5F5F5);
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.inputBaseView];
    [self.inputBaseView addSubview:self.textView];
    [self.inputBaseView addSubview:self.submitButton];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillShow:) name:UIKeyboardWillShowNotification object:nil];

    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyBoardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

    //MARK: - Target Action
- (void)submitButtonAction: (UIButton *)button {
    if ([EJSUserModel userModel]) {
        if (self.textView.text.length >0 && ![self.textView.text isEqualToString:@"请输入评论"]) {
            [self commentRequest];
        }else {
            [[HUDHelper sharedInstance]tipMessage:@"请输入评论内容"];
        }
    }else {
        [[HUDHelper sharedInstance]tipMessage:@"请先登录"];
    }
}

- (void)commentRequest{
    [SVProgressHUD show];
    [self.submitButton setEnabled:NO];
    EJSClubCommentRequest *request = [EJSClubCommentRequest new];
    request.content = self.textView.text;
    request.moment_id = [XOClubViewModel shared].clubMessageModel.momentId;

    FlyWeakSelf
    [request asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [SVProgressHUD dismiss];
        [weakSelf.submitButton setEnabled:YES];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateClubList" object:nil];
        [weakSelf.navigationController popViewControllerAnimated:YES];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance]tipMessage:@"发现某些错误,评论失败,请稍后再试"];
        [weakSelf.submitButton setEnabled:YES];
        [SVProgressHUD dismiss];
    }];
}

    //MARK: - KeyBorad Notification
    //键盘升起，view向上偏移
- (void)keyBoardWillShow:(NSNotification *)notification
{
    CGFloat duration = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect value = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];

    [UIView animateWithDuration:duration animations:^{
        [self.inputBaseView setMj_y:self.inputBaseView.frame.origin.y - value.size.height];
    }];
}

    //键盘落下，view向下偏移
- (void)keyBoardWillHide:(NSNotification *)notification
{
    CGFloat duration = [[notification.userInfo valueForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue];
    CGRect value = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [UIView animateWithDuration:duration animations:^{
        [self.inputBaseView setMj_y: self.view.bounds.size.height - BaseViewHeight];
    }];

}

    //MARK: - UITableView Datasource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else {
        return  [XOClubViewModel shared].clubMessageModel.commentTotal.intValue;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        XOClubMessageCell * cell = [tableView dequeueReusableCellWithIdentifier:@"CommentXOClubMessageCell" forIndexPath:indexPath];
        cell.messageModel = [XOClubViewModel shared].clubMessageModel;
        return cell;
    }else {
        XOClubDetailCommentCell * cell = [tableView dequeueReusableCellWithIdentifier:@"XOClubDetailCommentCell" forIndexPath:indexPath];
        cell.commentModel = [XOClubViewModel shared].clubMessageModel.comments[indexPath.row];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        EJSClubMessageModel *model = [XOClubViewModel shared].clubMessageModel;
        CGFloat conpletedHeight = model.rowHeight;
        CGFloat newHeight = conpletedHeight - model.likesHeight - model.commentsHeight - 35 - (2 * CommonMargin);
        return newHeight;
    }else {
        return UITableViewAutomaticDimension;
    }
}

    //MARK: - UITextViewDelegate
- (void)textViewDidBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@"请输入评论"]) {
        textView.textColor = AppMainColor;
        textView.text = @"";
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView {
    if (textView.text.length == 0) {
        textView.textColor = UIColor.darkTextColor;
        textView.text = @"请输入评论";
    }
}

@end
